const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.post('/add-class', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { title, description, parent_id, is_delete } = req.body
  if (
    !Bee.StringUtils.isNotBlank(title) ||
    !Bee.StringUtils.isNumber(parent_id) ||
    !Bee.StringUtils.isNumber(is_delete)
  )
    return handleError(10003, '参数错误')

  const [addClassError, addClassSuccess] = await to(
    db.query(
      'INSERT INTO class (title, description, created_time, parent_id, is_delete, updated_time) VALUES (?, ?, NOW(), ?, ?, NOW())',
      [title, description ? description : '', parent_id, is_delete]
    )
  )
  if (addClassError || !addClassSuccess) return handleError(-1, addClassError)

  return resp.json({
    code: 0,
    msg: status_code[0],
  })
})

module.exports = router
